var express = require('express');
var router = express.Router();
var pool = require("../db/mysql");

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('httpsindex', { title: 'Express' });
});

/* GET home page. */
router.post('/user', function (req, res, next) {
  var page = req.body.page;
  var limit = req.body.limit;
  var inviteCode = req.body.inviteCode;
  var name = req.body.name;
  var eth = req.body.eth;
  if (!page) {
    page = 1;
  }
  if (!limit) {
    limit = 10;
  }
  var startRow = (page - 1) * limit;
  var countSql = "select count(0) as count from base_invite";
  var sql = "select * from base_invite";
  if(name){
    countSql += " where WECHAT_NAME='"+name+"'"
    sql += " where WECHAT_NAME='"+name+"'"
  }
  if(inviteCode){
    if(countSql.indexOf("where") === -1){
      countSql += " where INVITE_CODE='"+inviteCode+"'"
      sql += " where INVITE_CODE='"+inviteCode+"'"
    }else{
      countSql += " and INVITE_CODE='"+inviteCode+"'"
      sql += " and INVITE_CODE='"+inviteCode+"'"
    }
  }
  if(eth){
    if(countSql.indexOf("where") === -1){
      countSql += " where ETH_ADDRESS='"+eth+"'"
      sql += " where ETH_ADDRESS='"+eth+"'"
    }else{
      countSql += " and ETH_ADDRESS='"+eth+"'"
      sql += " and ETH_ADDRESS='"+eth+"'"
    }
  }
  sql += " limit "+startRow+","+limit;
  console.log(countSql);
  console.log(sql);
  var count = 0;
  var countFun = (resolve, reject) => {
    pool.query(countSql, function (error, results, fields) {
      if (error) reject(error);
      if(results&&results[0]){
        resolve(results[0].count);
      }else{
        resolve(0);
      }
    });
  }

  var sqlFun = (resolve, reject) => {
    pool.query(sql, function (error, results, fields) {
      if (error) reject(error);
      resolve(results);
    });
  }

  new Promise(countFun).then((data) => {
    count = data;
    return new Promise(sqlFun);
  }).then((data) => {
    var jsonpData = {code:0,msg:"",count:count,data:data};
    res.jsonp(jsonpData);
    res.end();
  }).catch((error) => {
    console.log(error);
    var jsonpData = {code:1,msg:"查询出错",count:0,data:[]};
    res.jsonp(jsonpData);
    res.end();    
  });
});

module.exports = router;
